package com.livestocksolutions.intent;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;

import com.livestocksolutions.Bovine;
import com.livestocksolutions.Chemical;
import com.livestocksolutions.Feed;
import com.livestocksolutions.Group;
import com.livestocksolutions.LivestockSolutions;
import com.livestocksolutions.Location;
import com.livestocksolutions.Medicine;
import com.livestocksolutions.Mob;
import com.livestocksolutions.Observation;
import com.livestocksolutions.Owner;
import com.livestocksolutions.Paddock;

import com.livestocksolutions.R;
import com.livestocksolutions.ui.ListCattleArrayAdapter;
import com.livestocksolutions.ui.ListChemicalArrayAdapter;
import com.livestocksolutions.ui.ListChemicineArrayAdapter;
import com.livestocksolutions.ui.ListFeedArrayAdapter;
import com.livestocksolutions.ui.ListGroupArrayAdapter;
import com.livestocksolutions.ui.ListGroupMobArrayAdapter;
import com.livestocksolutions.ui.ListLocationArrayAdapter;
import com.livestocksolutions.ui.ListMedicineArrayAdapter;
import com.livestocksolutions.ui.ListMobArrayAdapter;
import com.livestocksolutions.ui.ListObservationArrayAdapter;
import com.livestocksolutions.ui.ListPaddockArrayAdapter;
import com.livestocksolutions.ui.ViewCattleArrayAdapter;
import com.livestocksolutions.ui.ViewGroupMobArrayAdapter;
import com.livestocksolutions.ui.ViewLocationPaddockArrayAdapter;
import com.livestocksolutions.ui.ViewObservationArrayAdapter;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/* -- Version History --
 *  1.0 : 22 July 2012 - Initial version.
 *  
 *  1.1 : 13 August 2012 - Created super class BaseActivity to hold all methods that are
 *                         standard across Activities
 */

/**
 * This class manages the initial home screen and lists before selecting various items
 * from any of the lists
 * @author Adam Parr
 * @version 1.1
 * 
 * @.modified 28 September 2012
 */
public class HomeActivity extends BaseActivity {
	public static final int HOME 					=  0;
	
	public static final int CATTLELIST 				=  1;
	public static final int GROUPMOBLIST 			=  2;
	public static final int PADDOCKLIST 			=  3;
	public static final int CHEMICINELIST 			=  4;
	public static final int FEEDLIST 				=  5;
	public static final int BUSINESSLOCATIONLIST 	=  6;
	
	/**
	 * Stores the reference to the XML layout template for each view
	 * @see #HOME
	 * @see #CATTLELIST
	 * @see #GROUPMOBLIST
	 * @see #PADDOCKLIST
	 * @see #CHEMICINELIST
	 * @see #FEEDLIST
	 * @see #BUSINESSLOCATIONLIST
	 */
	public static final Integer[] RESOURCEID = new Integer[]{
		R.layout.list_single,
		R.layout.list_single,
		R.layout.list_double,
		R.layout.list_single,
		R.layout.list_double,
		R.layout.list_single,
		R.layout.list_double
	};
	
	/**
	 * Constructor
	 */
	public HomeActivity() {
		super(RESOURCEID);
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if(stack.size()==0){
    		// No previous frame had been visited, show home frame
    		currentState.putInt(STATEID,HOME);
    		setContentView(RESOURCEID[HOME]);
    	}
        if(savedInstanceState==null){
        	// Assume initial loading
        	LinearLayout view = (LinearLayout) findViewById(R.id.listView);
			view.removeAllViews();
			view.addView(getLoading(view));
        	new LoadData().execute(null, null, null);
        }
        
        // Update the date format to system default value
 		if(LivestockSolutions.getDateFormat()==null){
 			LivestockSolutions.setDateFormat(getDateFormat());
 		}
    }
    
    /**
     * Loads the initial data on a separate thread so that the UI thread is not
     * frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class LoadData extends AsyncTask<String, Integer, Long> {
        @Override
		protected Long doInBackground(String... strings) {
        	if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
	        	File folder = Environment.getExternalStoragePublicDirectory("Livestock Solutions");
	        	folder.mkdirs();
	        	LivestockSolutions.setStorageLocation(folder);
	        	if(!LivestockSolutions.initilise()){
	        		LivestockSolutions.ignoreLock();
	        	}
	        	return 0L;
        	}
        	return 1L;
        }
        
        @Override
		protected void onPostExecute(final Long result) {
        	if(result>0){
        		Toast.makeText(HomeActivity.this, getResources().getString(R.string.message_noExternalCardDetected), Toast.LENGTH_LONG).show();
        	}
        }
    }

	@Override
    public boolean frameSelection(int frame) {
        switch (frame) {
        	case R.id.menu_search:
    			if(android.os.Build.VERSION_CODES.HONEYCOMB<=android.os.Build.VERSION.SDK_INT){
    				// Version of Android is a version that shows the search bar above
    				return false;
    			}
    			return onSearchRequested();
        	case R.id.menu_add_bovine:
	        	// Add a blank Bovine, Start a new Bovine
	    		Intent intent = new Intent(HomeActivity.this, BovineActivity.class);
	    		intent.putExtra(ITEMID, Long.parseLong("-1"));
	    		startActivityForResult(intent, NEW);
	    		stack.push(currentState);
		        //$FALL-THROUGH$
			case R.id.menu_cattle:
	        	showView(CATTLELIST,currentState);
	            break;
	        case R.id.menu_group_mob:
	        	showView(GROUPMOBLIST,currentState);
	        	break;
	        case R.id.menu_paddock:
	        	showView(PADDOCKLIST,currentState);
	        	break;
	        case R.id.menu_chemicine:
	        	showView(CHEMICINELIST,currentState);
	        	break;
	        case R.id.menu_feed:
	        	showView(FEEDLIST,currentState);
	        	break;
	        case R.id.menu_business_location:
	        	showView(BUSINESSLOCATIONLIST,currentState);
	        	break;
	        default:
	        	return super.frameSelection(frame);
        }
        return true;
    }
	
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
    	if(resultCode == RESULT_OK){
	    	switch (requestCode){
		    	case EXISTING:
		    		drawCattleList();
		    		break;
		    	case NEW:
		    		drawCattleList();
		    		break;
	    	}
    	}
    }
    
    @Override
    public boolean constructFrame(int view) {
    	switch (view) {
	    	case HOME:
	    		drawHomeList();
	            break;
	        case CATTLELIST:
	        	drawCattleList();
	            break;
	        case GROUPMOBLIST:
	        	drawGroupMobList();
	        	break;
	        case PADDOCKLIST:
	        	drawPaddockList();
	        	break;
	        case CHEMICINELIST:
	        	drawChemicineList();
	        	break;
	        case FEEDLIST:
	        	drawFeedList();
	        	break;
	        case BUSINESSLOCATIONLIST:
	        	drawBusinessLocationList();
	        	break;
	        default:
	            return false;
    	}
    	return true;
    }
    
    /**
     * Draw a list of high ranking Observations that link to their owning Objects.
     */
    private void drawHomeList(){
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_observation);
    	((TextView)((LinearLayout)findViewById(R.id.selectiveListTitle)).findViewById(R.id.title)).setText(getResources().getString(R.string.observation_critical));
    	
    	LinearLayout observationView = (LinearLayout) findViewById(R.id.listView);
    	observationView.removeAllViews();
    	observationView.addView(getLoading(observationView));
    	
    	new DrawHomeList().execute(null, null, null);
    }
    
    /**
     * Gathers data for the list of High Priority Observations on a separate thread
     * so that the UI thread is not frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class DrawHomeList extends AsyncTask<String, Integer, ListObservationArrayAdapter> {
        @Override
		protected ListObservationArrayAdapter doInBackground(String... strings) {
        	Observation[] observationArray = LivestockSolutions.getObservations();
        	Arrays.sort(observationArray, observationComparator);
        	ArrayList<String[]> observationValues = new ArrayList<String[]>();
        	for(int x=0; x<observationArray.length; x++){
        		if(observationArray[x].getPriority()<=ViewObservationArrayAdapter.TYPE_WATCH){
        			break;
        		}
        		String[] s = new String[ViewObservationArrayAdapter.SIZE];
        		s[ViewObservationArrayAdapter.ID] =  String.valueOf(observationArray[x].getID());
        		s[ViewObservationArrayAdapter.DATE] = String.valueOf(observationArray[x].getDate().getTime());
        		s[ViewObservationArrayAdapter.VALUE] = observationArray[x].getComment();
        		s[ViewObservationArrayAdapter.TYPE] = String.valueOf(observationArray[x].getPriority());
        		observationValues.add(s);
        	}
        	String[][] observations = observationValues.toArray(new String[][]{});
        	return new ListObservationArrayAdapter(HomeActivity.this, observations);
        }
        @Override
		protected void onPostExecute(final ListObservationArrayAdapter observation) {
        	LinearLayout observationView = (LinearLayout) findViewById(R.id.listView);
        	observationView.removeAllViews();
        	if(observation.getCount()>0){
    	    	observation.setRoot(observationView);
    	    	for(int x=0; x< observation.getCount(); x++){
    	    		View v = observation.getView(x, null, observationView);
    	    		v.setOnClickListener(new View.OnClickListener() {
    					public void onClick(View v) {
    						Observation o =LivestockSolutions.getObservationByID(Long.parseLong(observation.getItem(v.getId())[ViewCattleArrayAdapter.ID]));
    						Object owner = o.getOwner();
    						Intent intent = new Intent();
    						long id = -1;
    						if(owner instanceof Bovine){
    							id=((Bovine) owner).getID();
    							intent = new Intent(HomeActivity.this, BovineActivity.class);
    						}else if(owner instanceof Location){
    							id=((Location) owner).getID();
    							if(owner instanceof Paddock){
    								intent = new Intent(HomeActivity.this, PaddockActivity.class);
    							}else{
    								intent = new Intent(HomeActivity.this, LocationActivity.class);
    							}
    						}if(owner instanceof Group){
    							id=((Group) owner).getID();
    							if(owner instanceof Mob){
    								intent = new Intent(HomeActivity.this, MobActivity.class);
    							}else{
    								intent = new Intent(HomeActivity.this, GroupActivity.class);
    							}
    						}
    						
    						intent.putExtra(ITEMID, id);
    						startActivityForResult(intent, NONE);
    					}
    				});
    	    		observationView.addView(v,x);
    	    	}
        	}else{
        		observationView.addView(inflateLayout(R.layout.item_none,observationView));
        		((TextView)findViewById(R.id.listItemNone)).setText(getResources().getString(R.string.observation_displayNone));
        	}
        }
    }
    
    /**
     * Show the list of cattle
     */
    private void drawCattleList() {
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_cattle);
    	
    	LinearLayout cattleView = (LinearLayout) findViewById(R.id.listView);
    	cattleView.removeAllViews();
    	cattleView.addView(getLoading(cattleView));
    	
    	new DrawCattleList().execute(null, null, null);
    }
    
    /**
     * Gathers data for the list of Bovines on a separate thread so that the UI
     * thread is not frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class DrawCattleList extends AsyncTask<String, Integer, ListCattleArrayAdapter> {
        @Override
		protected ListCattleArrayAdapter doInBackground(String... strings) {
        	Bovine[] bovineArray = LivestockSolutions.getActiveBovines();
        	Arrays.sort(bovineArray, bovineComparator);
        	String[][] bovineValues = new String[bovineArray.length][ListCattleArrayAdapter.SIZE];
        	for(int x=0; x<bovineArray.length; x++){
        		Date d = bovineArray[x].getDob();
        		bovineValues[x][ViewCattleArrayAdapter.ID] =  String.valueOf(bovineArray[x].getID());
        		bovineValues[x][ViewCattleArrayAdapter.VISUALID] = bovineArray[x].getEartag().getEartagID();
        		bovineValues[x][ViewCattleArrayAdapter.NLISRFID] = bovineArray[x].getEartag().getRfID();
        		bovineValues[x][ViewCattleArrayAdapter.DOB] = d!=null?String.valueOf(d.getTime()):"";
        	}
        	return new ListCattleArrayAdapter(HomeActivity.this, bovineValues);
        }
        @Override
		protected void onPostExecute(final ListCattleArrayAdapter cattle) {
        	LinearLayout cattleView = (LinearLayout) findViewById(R.id.listView);
        	cattleView.removeAllViews();
        	if(cattle.getCount()>0){
    	    	cattle.setRoot(cattleView);
    	    	for(int x=0; x< cattle.getCount(); x++){
    	    		View v = cattle.getView(x, null, cattleView);
    	    		v.setOnClickListener(new View.OnClickListener() {
    					public void onClick(View v) {
    						Intent intent = new Intent(HomeActivity.this, BovineActivity.class);
    						intent.putExtra(ITEMID, Long.parseLong(cattle.getItem(v.getId())[ViewCattleArrayAdapter.ID]));
    						startActivityForResult(intent, NONE);
    					}
    				});
    	    		cattleView.addView(v,x);
    	    	}
        	}else{
        		cattleView.addView(inflateLayout(R.layout.item_none,cattleView));
        	}
        }
    }
    
    /**
     * Show the list Groups and Mobs
     */
    private void drawGroupMobList(){
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_mob);
    	setupListTitle(R.id.selectiveListTitleTwo, R.layout.list_item_group);
    	
    	LinearLayout mobView = (LinearLayout) findViewById(R.id.listView);
    	mobView.removeAllViews();
    	mobView.addView(getLoading(mobView));
    	
    	LinearLayout groupView = (LinearLayout) findViewById(R.id.listViewTwo);
    	groupView.removeAllViews();
    	groupView.addView(getLoading(groupView));
    	
    	new DrawMobList().execute(null, null, null);
    	new DrawGroupList().execute(null, null, null);

    }
    
    /**
     * Gathers data for the list of Mobs on a separate thread so that the UI
     * thread is not frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class DrawMobList extends AsyncTask<String, Integer, ListMobArrayAdapter> {
        @Override
		protected ListMobArrayAdapter doInBackground(String... strings) {
        	Mob[] mobArray = LivestockSolutions.getOnlyMobs();
        	Arrays.sort(mobArray, groupComparator);
        	String[][] mobValues = new String[mobArray.length][ListMobArrayAdapter.SIZE];
        	for(int x=0; x<mobArray.length; x++){
        		mobValues[x][ViewGroupMobArrayAdapter.ID] =  String.valueOf(mobArray[x].getID());
        		mobValues[x][ViewGroupMobArrayAdapter.NAME] = mobArray[x].getName();
        		mobValues[x][ListGroupMobArrayAdapter.COUNT] = String.valueOf(mobArray[x].getBovineList().length);
        		mobValues[x][ListMobArrayAdapter.LOCATION] = mobArray[x].getLocation()!=null?mobArray[x].getLocation().getName():getResources().getString(R.string.message_noText,R.string.paddock_none);
        	}
        	return new ListMobArrayAdapter(HomeActivity.this, mobValues);
        }
        @Override
		protected void onPostExecute(final ListMobArrayAdapter mob) {
        	LinearLayout mobView = (LinearLayout) findViewById(R.id.listView);
        	mobView.removeAllViews();
        	if(mob.getCount()>0){
    	    	mob.setRoot(mobView);
    	    	for(int x=0; x< mob.getCount(); x++){
    	    		View v = mob.getView(x, null, mobView);
    	    		v.setOnClickListener(new View.OnClickListener() {
    					public void onClick(View v) {
    						Intent intent = new Intent(HomeActivity.this, MobActivity.class);
    						intent.putExtra(ITEMID, Long.parseLong(mob.getItem(v.getId())[ViewGroupMobArrayAdapter.ID]));
    						startActivityForResult(intent, NONE);
    					}
    				});
    	    		mobView.addView(v,x);
    	    	}
    	    }else{
    	    	mobView.addView(inflateLayout(R.layout.item_none,mobView));
    		}
        }
    }
    
    /**
     * Gathers data for the list of Groups on a separate thread so that the UI
     * thread is not frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class DrawGroupList extends AsyncTask<String, Integer, ListGroupArrayAdapter> {
        @Override
		protected ListGroupArrayAdapter doInBackground(String... strings) {
        	Group[] groupArray = LivestockSolutions.getOnlyGroups();
        	Arrays.sort(groupArray, groupComparator);
        	String[][] groupValues = new String[groupArray.length][ViewGroupMobArrayAdapter.SIZE];
        	for(int x=0; x<groupValues.length; x++){
        		groupValues[x][ViewGroupMobArrayAdapter.ID] =  String.valueOf(groupArray[x].getID());
        		groupValues[x][ViewGroupMobArrayAdapter.NAME] = groupArray[x].getName();
        		groupValues[x][ListGroupMobArrayAdapter.COUNT] = String.valueOf(groupArray[x].getBovineList().length);
        	}
        	return new ListGroupArrayAdapter(HomeActivity.this, groupValues);
        }
        @Override
		protected void onPostExecute(final ListGroupArrayAdapter group) {
        	LinearLayout groupView = (LinearLayout) findViewById(R.id.listViewTwo);
        	groupView.removeAllViews();
        	if(group.getCount()>0){
    	    	group.setRoot(groupView);
    	    	for(int x=0; x< group.getCount(); x++){
    	    		View v = group.getView(x, null, groupView);
    	    		v.setOnClickListener(new View.OnClickListener() {
    					public void onClick(View v) {
    						Intent intent = new Intent(HomeActivity.this, GroupActivity.class);
    						intent.putExtra(ITEMID, Long.parseLong(group.getItem(v.getId())[ViewGroupMobArrayAdapter.ID]));
    						startActivityForResult(intent, NONE);
    					}
    				});
    	    		groupView.addView(v,x);
    	    	}
        	}else{
        		groupView.addView(inflateLayout(R.layout.item_none,groupView));
    		}
        }
    }
    
    /**
     * Show the list Paddocks
     */
	private void drawPaddockList() {
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_paddock);
    	
    	LinearLayout paddockView = (LinearLayout) findViewById(R.id.listView);
    	paddockView.removeAllViews();
    	paddockView.addView(getLoading(paddockView));
    	
    	new DrawPaddockList().execute(null, null, null);
    }
	
	/**
     * Gathers data for the list of Paddocks on a separate thread so that the UI
     * thread is not frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class DrawPaddockList extends AsyncTask<String, Integer, ListPaddockArrayAdapter> {
        @Override
		protected ListPaddockArrayAdapter doInBackground(String... strings) {
        	Paddock[] paddockArray = LivestockSolutions.getOnlyPaddocks();
    		Arrays.sort(paddockArray, locationComparator);
        	String[][] paddockValues = new String[paddockArray.length][ViewLocationPaddockArrayAdapter.SIZE];
        	for(int x=0; x<paddockValues.length; x++){
        		paddockValues[x][ViewLocationPaddockArrayAdapter.ID] =  String.valueOf(paddockArray[x].getID());
        		paddockValues[x][ViewLocationPaddockArrayAdapter.NAME] = paddockArray[x].getName();
        	}
        	return new ListPaddockArrayAdapter(HomeActivity.this, paddockValues);
        }
        @Override
		protected void onPostExecute(final ListPaddockArrayAdapter paddock) {
        	LinearLayout paddockView = (LinearLayout) findViewById(R.id.listView);
        	paddockView.removeAllViews();
        	if(paddock.getCount()>0){
    	    	paddock.setRoot(paddockView);
    	    	for(int x=0; x< paddock.getCount(); x++){
    	    		View v = paddock.getView(x, null, paddockView);
    	    		v.setOnClickListener(new View.OnClickListener() {
    					public void onClick(View v) {
    						Intent intent = new Intent(HomeActivity.this, PaddockActivity.class);
    						intent.putExtra(ITEMID, Long.parseLong(paddock.getItem(v.getId())[ViewLocationPaddockArrayAdapter.ID]));
    						startActivityForResult(intent, NONE);
    					}
    				});
    	    		paddockView.addView(v,x);
    	    	}
    		}else{
    			paddockView.addView(inflateLayout(R.layout.item_none,paddockView));
    		}
        }
    }
    
	/**
	 * Draw the list of Chemicals and Medicines that have been purchased.
	 */
	private void drawChemicineList() {
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_medicine);
    	setupListTitle(R.id.selectiveListTitleTwo, R.layout.list_item_chemical);
    	
    	LinearLayout medicineView = (LinearLayout) findViewById(R.id.listView);
    	medicineView.removeAllViews();
    	medicineView.addView(getLoading(medicineView));
    	
    	LinearLayout chemicalView = (LinearLayout) findViewById(R.id.listViewTwo);
    	chemicalView.removeAllViews();
    	chemicalView.addView(getLoading(chemicalView));
    	
    	new DrawMedicineList().execute(null, null, null);
    	new DrawChemicalList().execute(null, null, null);
	}
	
    /**
     * Gathers data for the list of Medicines on a separate thread so that the UI
     * thread is not frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class DrawMedicineList extends AsyncTask<String, Integer, ListMedicineArrayAdapter> {
        @Override
		protected ListMedicineArrayAdapter doInBackground(String... strings) {
        	Medicine[] medicineArray = LivestockSolutions.getOnlyMedicines();
        	Arrays.sort(medicineArray, usableItemComparator);
    		String[][] medicineValues = new String[medicineArray.length][ListChemicineArrayAdapter.SIZE];
        	for(int x=0; x<medicineValues.length; x++){
        		medicineValues[x][ListChemicineArrayAdapter.ID] =  String.valueOf(medicineArray[x].getID());
        		medicineValues[x][ListChemicineArrayAdapter.NAME] = medicineArray[x].getName();
        		medicineValues[x][ListChemicineArrayAdapter.PURCHASEDATE] = medicineArray[x].getPurchaseDate()!=null?String.valueOf(medicineArray[x].getPurchaseDate().getTime()):"";
        	}
        	return new ListMedicineArrayAdapter(HomeActivity.this, medicineValues);
        }
        @Override
		protected void onPostExecute(final ListMedicineArrayAdapter medicine) {
        	LinearLayout medicineView = (LinearLayout) findViewById(R.id.listView);
        	medicineView.removeAllViews();
        	if(medicine.getCount()>0){
    	    	medicine.setRoot(medicineView);
    	    	for(int x=0; x< medicine.getCount(); x++){
    	    		View v = medicine.getView(x, null, medicineView);
    	    		v.setOnClickListener(new View.OnClickListener() {
    					public void onClick(View v) {
    						Intent intent = new Intent(HomeActivity.this, ChemicineActivity.class);
    						intent.putExtra(ITEMID, Long.parseLong(medicine.getItem(v.getId())[ListChemicineArrayAdapter.ID]));
    						startActivityForResult(intent, NONE);
    					}
    				});
    	    		medicineView.addView(v,x);
    	    	}
    		}else{
    			medicineView.addView(inflateLayout(R.layout.item_none,medicineView));
    		}
        }
    }
    
    /**
     * Gathers data for the list of Chemicals on a separate thread so that the UI
     * thread is not frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class DrawChemicalList extends AsyncTask<String, Integer, ListChemicalArrayAdapter> {
        @Override
		protected ListChemicalArrayAdapter doInBackground(String... strings) {
        	Chemical[] chemicalArray = LivestockSolutions.getOnlyChemicals();
    		Arrays.sort(chemicalArray, usableItemComparator);
    		String[][] chemicalValues = new String[chemicalArray.length][ListChemicineArrayAdapter.SIZE];
        	for(int x=0; x<chemicalValues.length; x++){
        		chemicalValues[x][ListChemicineArrayAdapter.ID] =  String.valueOf(chemicalArray[x].getID());
        		chemicalValues[x][ListChemicineArrayAdapter.NAME] = chemicalArray[x].getName();
        		chemicalValues[x][ListChemicineArrayAdapter.PURCHASEDATE] = chemicalArray[x].getPurchaseDate()!=null?String.valueOf(chemicalArray[x].getPurchaseDate().getTime()):"";
        	}
        	return new ListChemicalArrayAdapter(HomeActivity.this, chemicalValues);
        }
        @Override
		protected void onPostExecute(final ListChemicalArrayAdapter chemical) {
        	LinearLayout chemicalView = (LinearLayout) findViewById(R.id.listViewTwo);
    	    chemicalView.removeAllViews();
    	    if(chemical.getCount()>0){
    	    	chemical.setRoot(chemicalView);
    	    	for(int x=0; x< chemical.getCount(); x++){
    	    		View v = chemical.getView(x, null, chemicalView);
    	    		v.setOnClickListener(new View.OnClickListener() {
    					public void onClick(View v) {
    						Intent intent = new Intent(HomeActivity.this, ChemicineActivity.class);
    						intent.putExtra(ITEMID, Long.parseLong(chemical.getItem(v.getId())[ListChemicineArrayAdapter.ID]));
    						startActivityForResult(intent, NONE);
    					}
    				});
    	    		chemicalView.addView(v,x);
    	    	}
    		}else{
    			chemicalView.addView(inflateLayout(R.layout.item_none,chemicalView));
    		}
        }
    }
	
	private void drawFeedList() {
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_feed);
    	
    	LinearLayout feedView = (LinearLayout) findViewById(R.id.listView);
    	feedView.removeAllViews();
    	feedView.addView(getLoading(feedView));
    	
    	new DrawFeedList().execute(null, null, null);
	}
	
    /**
     * Gathers data for the list of Feeds on a separate thread so that the UI
     * thread is not frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class DrawFeedList extends AsyncTask<String, Integer, ListFeedArrayAdapter> {
        @Override
		protected ListFeedArrayAdapter doInBackground(String... strings) {
        	Feed[] feedArray = LivestockSolutions.getOnlyFeeds();
    		Arrays.sort(feedArray, usableItemComparator);
    		String[][] feedValues = new String[feedArray.length][ListChemicineArrayAdapter.SIZE];
        	for(int x=0; x<feedValues.length; x++){
        		feedValues[x][ListChemicineArrayAdapter.ID] =  String.valueOf(feedArray[x].getID());
        		feedValues[x][ListChemicineArrayAdapter.NAME] = feedArray[x].getName();
        		feedValues[x][ListChemicineArrayAdapter.PURCHASEDATE] = feedArray[x].getPurchaseDate()!=null?String.valueOf(feedArray[x].getPurchaseDate().getTime()):"";
        	}
        	return new ListFeedArrayAdapter(HomeActivity.this, feedValues);
        }
        @Override
		protected void onPostExecute(final ListFeedArrayAdapter feed) {
        	LinearLayout feedView = (LinearLayout) findViewById(R.id.listView);
        	feedView.removeAllViews();
        	if(feed.getCount()>0){
    	    	feed.setRoot(feedView);
    	    	for(int x=0; x< feed.getCount(); x++){
    	    		View v = feed.getView(x, null, feedView);
    	    		v.setOnClickListener(new View.OnClickListener() {
    					public void onClick(View v) {
    						Intent intent = new Intent(HomeActivity.this, FeedActivity.class);
    						intent.putExtra(ITEMID, Long.parseLong(feed.getItem(v.getId())[ListChemicineArrayAdapter.ID]));
    						startActivityForResult(intent, NONE);
    					}
    				});
    	    		feedView.addView(v,x);
    	    	}
        	}else{
        		feedView.addView(inflateLayout(R.layout.item_none,feedView));
    		}
        }
    }
	
    private void drawBusinessLocationList() {
    	setupListTitle(R.id.selectiveListTitle, R.layout.list_item_location);
    	setupListTitle(R.id.selectiveListTitleTwo,R.layout.list_item_business);
    	
    	LinearLayout locationView = (LinearLayout) findViewById(R.id.listViewTwo);
    	locationView.removeAllViews();
    	locationView.addView(getLoading(locationView));
    	
    	new DrawLocationList().execute(null, null, null);
    	
    	LinearLayout OwnerView = (LinearLayout) findViewById(R.id.listView);
    	OwnerView.removeAllViews();
    	OwnerView.addView(getLoading(OwnerView));
    	
    	new DrawOwnerList().execute(null, null, null);
	}
    
    /**
     * Gathers data for the list of Locations on a separate thread so that the UI
     * thread is not frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class DrawLocationList extends AsyncTask<String, Integer, ListLocationArrayAdapter> {
        @Override
		protected ListLocationArrayAdapter doInBackground(String... strings) {
        	Location[] locationArray = LivestockSolutions.getOnlyLocations();
        	Arrays.sort(locationArray, locationComparator);
        	String[][] locationValues = new String[locationArray.length][ViewLocationPaddockArrayAdapter.SIZE];
        	for(int x=0; x<locationArray.length; x++){
        		locationValues[x][ViewLocationPaddockArrayAdapter.ID]=String.valueOf(locationArray[x].getID());
        		locationValues[x][ViewLocationPaddockArrayAdapter.NAME]=locationArray[x].getName();
        		locationValues[x][ViewLocationPaddockArrayAdapter.DESCRIPTION]=locationArray[x].getDescription();
        	}
        	return new ListLocationArrayAdapter(HomeActivity.this, locationValues);
        }
        @Override
		protected void onPostExecute(final ListLocationArrayAdapter location) {
        	LinearLayout locationView = (LinearLayout) findViewById(R.id.listView);
        	locationView.removeAllViews();
        	if(location.getCount()>0){
    	    	location.setRoot(locationView);
    	    	for(int x=0; x< location.getCount(); x++){
    	    		View v = location.getView(x, null, locationView);
    	    		v.setOnClickListener(new View.OnClickListener() {
    					public void onClick(View v) {
    						Intent intent = new Intent(HomeActivity.this, LocationActivity.class);
    						intent.putExtra(ITEMID, Long.parseLong(location.getItem(v.getId())[ViewLocationPaddockArrayAdapter.ID]));
    						startActivityForResult(intent, NONE);
    					}
    				});
    	    		locationView.addView(v,x);
    	    	}
    	    }else{
    	    	locationView.addView(inflateLayout(R.layout.item_none,locationView));
    		}
        }
    }
    
    /**
     * Gathers data for the list of Owners on a separate thread so that the UI
     * thread is not frozen for a long period of time.
     * @author Adam Parr
     * @.modified 28 September 2012
     */
    private class DrawOwnerList extends AsyncTask<String, Integer, ListLocationArrayAdapter> {
        @Override
		protected ListLocationArrayAdapter doInBackground(String... strings) {
        	Owner[] ownerArray = LivestockSolutions.getOwners();
        	Arrays.sort(ownerArray, ownerComparator);
        	String[][] ownerValues = new String[ownerArray.length][ViewLocationPaddockArrayAdapter.SIZE];
        	for(int x=0; x<ownerArray.length; x++){
        		ownerValues[x][ViewLocationPaddockArrayAdapter.ID]=String.valueOf(ownerArray[x].getID());
        		ownerValues[x][ViewLocationPaddockArrayAdapter.NAME]=ownerArray[x].getName();
        		if(ownerArray[x].getContacts().length>0){
        			ownerValues[x][ViewLocationPaddockArrayAdapter.DESCRIPTION]=ownerArray[x].getContacts()[0]!=null?ownerArray[x].getContacts()[0].getValue():"";
        		}
        	}
        	return new ListLocationArrayAdapter(HomeActivity.this, ownerValues);
        }
        @Override
		protected void onPostExecute(final ListLocationArrayAdapter owners) {
        	LinearLayout ownerView = (LinearLayout) findViewById(R.id.listViewTwo);
        	ownerView.removeAllViews();
        	if(owners.getCount()>0){
    	    	owners.setRoot(ownerView);
    	    	for(int x=0; x< owners.getCount(); x++){
    	    		View v = owners.getView(x, null, ownerView);
    	    		v.setOnClickListener(new View.OnClickListener() {
    					public void onClick(View v) {
    						Intent intent = new Intent(HomeActivity.this, OwnerActivity.class);
    						intent.putExtra(ITEMID, Long.parseLong(owners.getItem(v.getId())[ViewLocationPaddockArrayAdapter.ID]));
    						startActivityForResult(intent, NONE);
    					}
    				});
    	    		ownerView.addView(v,x);
    	    	}
    	    }else{
    	    	ownerView.addView(inflateLayout(R.layout.item_none,ownerView));
    		}
        }
    }
}